
#import "NewestAticleCtr.h"
#import "AticleheadCell.h"
#import "CommentCell.h"
#import "UIImageView+WebCache.h"
#import "AticleFootView.h"
#import "XLDataService.h"
#import "AticALLModel.h"
#import "DetailModel.h"
#import "ImgListModel.h"
#import "NEWAticListModel.h"
#import "Manager.h"
#import "PramasMontage.h"
#import "ChangyanSDK.h"
#import "ComCountModel.h"
#import "CommetModel.h"
#import "PassportModel.h"
#import "UserDataModel.h"
#import "TextPutView.h"
#import "OtherInformationCtrl.h"
#import "ArticleHeadNaviView.h"
#import "LoginController.h"
#import "ShareView.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "CYCommentModel.h"
#import "NewsSectionHeadView.h"
#import "MJRefresh.h"
CG_INLINE void AlertLog (NSString *titleStr,NSString *message,NSString *button1,NSString *button2)
{
    if(!titleStr)
        titleStr = @"";
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: titleStr
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: button1
                                              otherButtonTitles: button2,
                              nil];
    [alertView show];
    
}

@interface NewestAticleCtr ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate,TextPutViewDeleget,CommentReplyDeleget,PramClickDeleget,ArticleHeadNaviViewDeleget,ShareViewDeleget>
{
    UITableView *_tableview ;
    CGFloat _aticleHeadHight;//文章详情的高度；
    CGFloat _comentHight;//评论列表的高度
    AticALLModel *_allModel;//总Model
    DetailModel *_detaiModel;
    ImgListModel *_imgListModel;
    NEWAticListModel *_relateList;//相关文章Model
    NSInteger _comentCount;
    NSString *_TopicID;
    NSInteger _PageNo;
    UserDataModel *_userModel;
}
@property (nonatomic,strong) AticleFootView *footview;
@property (nonatomic,strong) NSMutableArray *commentAry;
@property (nonatomic,strong) NSArray *AtcImgList;
@property (nonatomic,strong) ArticleHeadNaviView *articleHeadview;
@property (nonatomic,assign) NSInteger comtId;
@property (nonatomic,assign) BOOL isComtClick;
@property (nonatomic,strong) TextPutView *mytexetView;//发表评论View
@property (nonatomic,strong) CommetModel *commentModel;
@property(nonatomic,strong) AticHeadView *AticNavView;
@property (nonatomic,assign) BOOL zanzan;
@property (nonatomic,strong)  ShareView *shareView;
@end

@implementation NewestAticleCtr

-(ShareView *)shareView{
    
    if (!_shareView) {
        CGFloat hhh = SCREEN_HEIGHT*0.5;
        if (kDIEIsIPhone4SOrLess) {
            hhh = SCREEN_HEIGHT*0.63;
        }
        
        if (kDIEIsIPhone5) {
            hhh = SCREEN_HEIGHT*0.53;
        }
        
        if (kDIEIsIPhone6P) {
            hhh = SCREEN_HEIGHT*0.47;
        }

        _shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - hhh, SCREEN_WIDTH, hhh)];
        _shareView.IsImageUrl = @"YES";
        _shareView.shareImageUrl =_detaiModel.share_img;
        _shareView.title = _detaiModel.title;
        _shareView.message =_detaiModel.share_message;
        _shareView.shareUrl = _detaiModel.share_url;
        _shareView.deleget = self;
    }
    return _shareView;
}

-(void)viewWillAppear:(BOOL)animated{
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
    StatusBlack;
    self.articleHeadview.isLogin = self.app.isLogin;
}

-(TextPutView *)mytexetView{
    if (!_mytexetView) {
        _mytexetView = [[TextPutView alloc]initWithFrame:self.view.bounds];
        _mytexetView.alpha = 0;
        _mytexetView.deleget = self;
        _mytexetView.NoFace = YES;
        [self.view addSubview:_mytexetView];
    }
    return _mytexetView;
}
#pragma mark--获取评论data
-(void)GetCommentData{
    //获取评论数量  主要目的是获取文章的 topicID  从而获得评论内容
    __block NSDictionary *dic = [NSDictionary dictionary];
    [ChangyanSDK getCommentCount:nil topicSourceID:self.AticleID topicUrl:nil completeBlock:^(CYStatusCode statusCode, NSString *responseStr)
     {
         dic =  [Manager dictionaryWithJsonString:responseStr];
         ComCountModel *model = [[ComCountModel alloc]initWithDictionary:dic[@"result"][_AticleID] error:nil];
         _TopicID = model.id;
         [self getTopicCommentsWhithTopicID:model.id AndPageNo:1];
     }];
}
#pragma mark--获取评论列表
-(void)getTopicCommentsWhithTopicID:(NSString *)topicID AndPageNo:(NSInteger)pageNo{
    
    [ChangyanSDK getTopicComments:topicID
                         pageSize:@"5"
                           pageNo:[NSString stringWithFormat:@"%ld",(long)pageNo]
                          orderBy:nil
                            style:nil
                            depth:nil
                          subSize:nil
                    completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {

                        NSDictionary *dic = [Manager dictionaryWithJsonString:responseStr];
                        
                        CYCommentModel *cyModel = [[CYCommentModel alloc]initWithDictionary:dic error:nil];
                        //显示评论数量
                        _comentCount = cyModel.cmt_cnt.integerValue;
                        [self PublishView];
                        [_commentAry addObjectsFromArray:cyModel.comments];
                        
                        [_tableview reloadData];
                        [_tableview.footer endRefreshing];
                        
                    }];
}

#pragma mark---下拉加载
-(void)loadMoreData{
    
    _PageNo ++;
    if (_commentAry.count<_comentCount) {
        
        [self getTopicCommentsWhithTopicID:_TopicID AndPageNo:_PageNo];
        
    }else{
        [_tableview.footer noticeNoMoreData];
    }
}

#pragma mark--发表评论
-(void)CommentWhithContent:(NSString *)content replyID:(NSString *)ReplyId{
    
    [ChangyanSDK submitComment:_TopicID
                       content:content
                       replyID:ReplyId
                         score:nil
                       appType:40
                       picUrls:nil
                      metadata:nil
                 completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                     
                     
                     if ([responseStr rangeOfString:@"id"].length!=0) {
                         [Manager GetHudWhithText:@"评论成功" AndFatherView:self.view];
                         [_commentAry removeAllObjects];
                         [self GetCommentData];
                         //一个section刷新
                         NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
                         [_tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                         
                          _mytexetView.inputBar.textView.text = @"";
                     }else{
                         [Manager GetHudWhithText:@"评论失败" AndFatherView:self.view];
                     }

                 }];
   }

#pragma mark--文章data
-(void)GetAFNt{
    
//    NSLog(@"文章详情url--%@",[PramasMontage AticleBidy:self.AticleID]);
    
    [[Manager sharedManager]RequestWhithURL:[PramasMontage AticleBidy:self.AticleID] AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if (!error) {
            _allModel = [[AticALLModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
            _detaiModel =_allModel.article;
            self.AtcImgList = _allModel.image_list;
            [self PublishView];
            [MBProgressHUD hideHUDForView:self.view];
            
            [UIView transitionWithView:self.view duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                
                [self CreactTableview];

            } completion:nil];
            
        }else{
            [MBProgressHUD hideHUDForView:self.view];
            [Manager GetHudWhithText:@"加载失败" AndFatherView:self.view];
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].statusBarStyle = 0;
    _PageNo =  1;
    self.view.backgroundColor = [UIColor whiteColor];
    _commentAry= [NSMutableArray array];
    [self NavView];
    [self creatHuD:nil];
    [self GetAFNt];
    [self GetCommentData];

}

#pragma mark--导航栏
-(void)NavView{
    
    self.articleHeadview = [[NSBundle mainBundle] loadNibNamed:@"ArticleHeadNaviView" owner:nil options:nil].lastObject;
    self.articleHeadview.frame = CGRectMake(0, 0, SCREEN_WIDTH, 64);
    self.articleHeadview.UserName = self.UserName;
    self.articleHeadview.AtcID = self.AticleID;
    self.articleHeadview.isLogin = self.app.isLogin;
    self.articleHeadview.deleget = self;
    self.articleHeadview.userModel = self.app.userModel;
    
    [self.view addSubview:self.articleHeadview];
}

-(void)backCLick{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark---收藏操作代理方法
-(void)collectMaseege:(BOOL)IsHUD Message:(NSString *)message{

    if (IsHUD) {
        [Manager GetHudWhithText:message AndFatherView:self.view];
    }else{
        [self ToLOgin];
    }
}
#pragma mark---分享操作
-(void)ShareClick{
       
    [self.shareView show];

}

#pragma mark---QQ空间单独事件
-(void)QzoneShare{
    NSString *utf8String = _detaiModel.share_url;
    NSString *title = _detaiModel.title;
    NSString *descriotion = _detaiModel.share_message;
    NSString *previewImageUrl = _detaiModel.share_url;
    
    NSArray* imageArray =@[previewImageUrl];
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKEnableUseClientShare];
        [shareParams SSDKSetupShareParamsByText:descriotion
                                         images:imageArray
                                            url:[NSURL URLWithString:utf8String]
                                          title:title
                                           type:SSDKContentTypeAudio];
        
        
        [ShareSDK share:SSDKPlatformSubTypeQZone
             parameters:shareParams
         onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
             
             if (state == SSDKResponseStateSuccess)
             {
                 [self.shareView fadeOut];
             }
             else if (state == SSDKResponseStateFail)
             {
                 AlertLog(@"", @"分享失败", @"确定", nil);
             }
             
             
         }];
        
    }
}

#pragma mark--底部发表View
-(void)PublishView{
    
    [_footview removeFromSuperview];
    _footview = [[AticleFootView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-60, SCREEN_WIDTH, 60)];
    _footview.backgroundColor = [UIColor whiteColor];
    [_footview.textbtn addTarget:self action:@selector(footCommetView) forControlEvents:UIControlEventTouchUpInside];
    [_footview.comBtn setTitle:[NSString stringWithFormat:@"%ld",(long)_comentCount] forState:UIControlStateNormal];
    [_footview.comBtn addTarget:self action:@selector(CommentClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_footview];
}

//点击显示评论位置  tableview滑到评论位置
-(void)CommentClick{
    
    NSIndexPath *indexPath;
    if (_comentCount!=0) {
        
        if (_commentAry.count>4) {
            indexPath =[NSIndexPath indexPathForRow:0 inSection:2];
        }else{
            indexPath=[NSIndexPath indexPathForRow:_commentAry.count-1 inSection:2];
        }

        [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:1 animated:YES];
    }
}

#pragma mark--发送评论的TextView代理
-(void)DidSender:(NSString *)sendText{
    [self IssueComentAction:sendText];
    
    self.mytexetView.alpha = 0;
    
    self.isComtClick = YES;
    
}

#pragma mark--底部点击评论，进入发表评论的TextView;

-(void)footCommetView{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        self.mytexetView.alpha = 1;
        self.mytexetView.inputBar.placeHolder = @"说点什么呢?";
        [self.mytexetView.inputBar.textView becomeFirstResponder];
    }else{

        [self ToLOgin];
    }
}

-(void)CreactTableview{
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0,53, SCREEN_WIDTH, SCREEN_HEIGHT-68.8) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableview];
    
    _tableview.separatorStyle =UITableViewCellSeparatorStyleNone;
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _tableview.delaysContentTouches = NO;
    [_tableview registerClass:[AticleheadCell class] forCellReuseIdentifier:@"AticleCell"];
    [_tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableview registerClass:[CommentCell class] forCellReuseIdentifier:@"commentCell"];
    
    _tableview.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.view sendSubviewToBack:_tableview];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableview.width, 1)];
    view.backgroundColor = [UIColor clearColor];
    _tableview.tableFooterView = view;
    _tableview.tableHeaderView = view;
    _tableview.sectionFooterHeight = 0.f;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        return 1;
    }else if (section==1){
    
        return _allModel.relate.count;
    }else{
        return _commentAry.count;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
/*一共分三组，文章，相关文章，钓友评论*/
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==2) {
        return 0;
    }else{
        return 20;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    /*头部高度，第0组为0，用于显示 相关文章，钓友评论  标题*/
    if (section==0) {
        return 0;
    }else{
        return SCREEN_HEIGHT*0.08;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NewsSectionHeadView *view = [[NSBundle mainBundle]loadNibNamed:@"NewsSectionHeadView" owner:nil options:nil].lastObject;
    view.frame  = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.08);
    
    if (section==1) {
         view.textShow.selected = NO;
        [view.textShow setTitle:@"相关文章" forState:UIControlStateNormal];

    }else{
        if (_commentAry.count!=0) {
            view.textShow.selected = NO;
        }else{
            view.textShow.selected = YES;
        }
    }
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
      
        return _aticleHeadHight+1;
        
    }else if (indexPath.section==1){
        return 44;
    }else{
        return _comentHight+1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        
        AticleheadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AticleCell"];
        cell.detaiModel = _detaiModel;
        cell.imageAry = self.AtcImgList;
        cell.deleget = self;
        [cell Refresh];
        
        _aticleHeadHight = cell.cellHhhh;
        
            return cell;
        
    }else if(indexPath.section==1){//相关文章Cell
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        _relateList = _allModel.relate[indexPath.row];
        cell.textLabel.text =[NSString stringWithFormat:@"%@", _relateList.title];
        cell.textLabel.font = font(SCREEN_WIDTH*0.05);
        [self Linview:CGRectMake(0, 0, SCREEN_WIDTH, 0.5) BackgroundColor:[UIColor lightGrayColor] AddView:cell.contentView];
        return cell;
        
    }else{//评论Cell
        
        CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
        cell.model = _commentAry[indexPath.row];
        cell.deleget = self;
        cell.RowOfcell  = indexPath.row;
        _comentHight = cell.cellhight;
        return cell;
    }
}

#pragma mark---文章点赞代理方法
-(void)PramClick{
 
    [self PramisAction];
}

#pragma mark----头像用户名点击代理方法
-(void)HeadAndNameClickWhithId:(NSString *)uid{
    OtherInformationCtrl *other = [OtherInformationCtrl new];
    other.uid = uid;
    [self.navigationController pushViewController:other animated:YES];
}

#pragma mark---畅言评论点赞操作
-(void)ComentPramClick:(NSString *)CommetID{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        
        if (self.app.ChangYanIsLogin) {
            
            [ChangyanSDK commentAction:1 topicID:_TopicID commentID:CommetID completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
            }];
        }
    }else{
            [self ToLOgin];
    }
}

-(void)ToLOgin{

    LoginController *login = [LoginController new];
    [self.navigationController pushViewController:login animated:YES];
}

#pragma mark--评论回复代理方法
-(void)CommentReply:(NSString *)ComentID UaerName:(NSString *)name Row:(NSInteger)row{
    
    [self footCommetView];
    self.mytexetView.inputBar.placeHolder =[NSString stringWithFormat:@"@%@",name];
    self.comtId = ComentID.integerValue;
    self.isComtClick = YES;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section==1) {
        NewestAticleCtr *new = [NewestAticleCtr new];
        NEWAticListModel *relateList = _allModel.relate[indexPath.row];
        new.AticleID = relateList.AtcID;
        [self.navigationController pushViewController:new animated:YES];
    }
}


#pragma mark---发表评论Action
-(void)IssueComentAction:(NSString *)Text{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        
        if (self.app.ChangYanIsLogin) {
            
            if (self.isComtClick == YES) {
                
                [self CommentWhithContent:Text replyID:[NSString stringWithFormat:@"%ld",(long)self.comtId]];
            }else{
                
                [self CommentWhithContent:Text replyID:nil];
            }
        }else{
            
            [Manager GetHudWhithText:@"您的评论没有成功，请检查您的网络" AndFatherView:self.view];
        }
    }
}

-(void)PramisAction{
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        
        NSDictionary *dic = @{@"uid":self.app.userModel.uid,@"article_id":_AticleID};
        [[Manager sharedManager]ResponseWhithURL:@"http://school.diaoyur.cn/article/good-post" AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        }];
    }else{
        [self ToLOgin];
    }
}

-(void)didReceiveMemoryWarning{
    
    [super didReceiveMemoryWarning];
    
    if ([self.view window] == nil) {
        
        self.view = nil;
    }
}


@end